'use strict';

const Service = require('egg').Service;

class HomeService extends Service {
  async list(opt) {
    opt = opt || {};
    let parent = opt.parent || ""; // 全部
    let keyword = opt.keyword || "";
    let param = {uid:opt.uid};
    if(parent){
        param.parent = parent;
    }
    if(keyword){
        let reg = new RegExp(keyword,"ig");
        param["$or"] = [{name:reg},{minm:reg}];
    }

    return  this.ctx.model.Person.find(param,{desc:0}).sort({"order": 1})
  }
  async add(opt){
    const {ctx,app} = this;
    opt = opt || {};
    var parent = opt.parent || "-1";
    opt.parent = parent;
    delete opt._id;
    delete opt.id;

    // 查询父节点
    if(parent != "-1"){
        let res = this.ctx.model.Person.findOne({"_id":parent});
        if(!res){
            return Promise.reject(app.resCode.parent);
        }
    }
    
    var person = new ctx.model.Person(opt);
    let res = await person.save();  
    if(parent != "-1"){
        await  ctx.model.Person.updateOne({"_id":parent},{$inc:{childs:1}})
    }
    return Promise.resolve(res);
  }

  async remove(id){
    const {ctx,app} = this;
    let res = await ctx.model.Person.deleteOne({"_id":id});
    await  ctx.model.Person.updateMany({parent:id},{$set:{parent:"-1"}});
    return Promise.resolve(res);
  }
  async update(opt){
    const {ctx,app} = this;
    opt = opt || {};
    let id = opt.id || opt._id || "";
    delete opt.id;
    delete opt._id;
    delete opt.uid;
    if(!id){
        return Promise.reject(app.resCode.params);
    }
    if(opt.parent){
        let old = await ctx.model.Person.findOne({"_id":id},{desc:0});
        if(!old){
            return Promise.reject(app.resCode.nonexist);
        }
        if(opt.parent != old.parent){
            // 改变了
            if(old.parent != "-1"){
                await  ctx.model.Person.updateOne({"_id":old.parent},{$inc:{childs:-1}})
            }
            if(opt.parent != "-1"){
                await  ctx.model.Person.updateOne({"_id":opt.parent},{$inc:{childs:1}})
            }
        }
    }
    return ctx.model.Person.updateOne({"_id":id},{$set:opt});
  }
  async info(id){
    return this.ctx.model.Person.findOne({"_id":id});
  }
  async updateOrders(opt){
    const {ctx,app} = this;
    opt = opt || {};
    let uid = opt.uid;
    let list = opt.list || [];
    if(list.length == 0){
      return Promise.resolve();
    }
    for(let i = 0; i < list.length; i++){
      let item = list[i];
      try{
        await ctx.model.Person.updateOne({uid,"_id":item.id},{$set:{order:item.order}});
      }catch(e){
        console.log(e);
      }
    }
    return Promise.resolve(list.length);
  }
}

module.exports = HomeService;